package com.jiangjiang.eshop.common.json;

import com.alibaba.fastjson.JSONObject;


/**
 * @Author Jianghaowen
 * @Date 2021/9/23
 * @Description: TODO
 * @Version V1.0
 **/
public class JsonExtractor {

    /**
     * 获取表达式对应的值
     *
     * @param targetJson        目标的json对象
     * @param jsonExtractSyntax 表达式
     * @return 值
     * @throws Exception
     */
    public Long getLong(JSONObject targetJson, String jsonExtractSyntax) {
        return Long.valueOf(String.valueOf(get(targetJson, jsonExtractSyntax)));
    }


    /**
     * 获取表达式对应的值
     *
     * @param targetJson        目标的json对象
     * @param jsonExtractSyntax 表达式
     * @return 值
     * @throws Exception
     */
    public static Integer getInteger(JSONObject targetJson, String jsonExtractSyntax) {
        return Integer.valueOf(String.valueOf(get(targetJson, jsonExtractSyntax)));
    }


    /**
     * 获取表达式对应的值
     *
     * @param targetJson        目标的json对象
     * @param jsonExtractSyntax 表达式
     * @return 值
     * @throws Exception
     */
    public String getString(JSONObject targetJson, String jsonExtractSyntax) {
        return String.valueOf(get(targetJson, jsonExtractSyntax));
    }

    /**
     * 获取表达式对应的值
     *
     * @param targetJson        目标的json对象
     * @param jsonExtractSyntax 表达式
     * @return 值
     * @throws Exception
     */
    private static Object get(JSONObject targetJson, String jsonExtractSyntax) {
        JsonExpression jsonExpression = JsonExtractSyntaxParser.parse(jsonExtractSyntax);
        return jsonExpression.interpret(new JsonExpressionContext(targetJson));
    }


    public static void main(String[] args) {
        String jsonString = "{\"a\":{\"A\":{\"price\":300}},\"b\":{\"B\":{\"price\":800}}}";
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Integer value = getInteger(jsonObject, "a/A/price");
        System.out.println(value);
    }
}
